import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';

/// BehaviorSubject每一个新加的监听，接收到的第一个数据都是上一个数据（再往前的数据不会监听到，只会缓存一个数据）。
/// 总结:每一个新加的监听接收到的第一条数据，是最近的那条数据（也就是只会缓存最近一条数据的意思）；对于单条数据而言，总是后加的监听先接收到。
class BehaviorSubjectDemoHome extends StatefulWidget {
  const BehaviorSubjectDemoHome({Key? key}) : super(key: key);

  @override
  _BehaviorSubjectDemoHomeState createState() =>
      _BehaviorSubjectDemoHomeState();
}

class _BehaviorSubjectDemoHomeState extends State<BehaviorSubjectDemoHome> {
  BehaviorSubject<String> _subject = BehaviorSubject<String>();
  BehaviorSubject<String> _testSubject = BehaviorSubject<String>();

  @override
  void initState() {
    super.initState();

    _testSubject.listen((event) => print("listener-1: $event"));
    _testSubject.add("Item1");

    _testSubject.listen((event) => print("listener-2: ${event.toUpperCase()}"));
    _testSubject.add("Item2");
    _testSubject.add("Item3");
  }

  @override
  void dispose() {
    super.dispose();
    _subject.close();
    _testSubject.close();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("BehaviorSubjectDemo"),
      ),
      body: Center(
        child: StreamBuilder(
          initialData: "loading...",
          stream: _subject,
          builder: (context, snapshot) {
            print("${snapshot.connectionState} - ${snapshot.data}");
            return Text("${snapshot.data}");
          },
        ),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FloatingActionButton(
            heroTag: 'add',
            onPressed: () {
              _subject.add("do add action");
            },
            child: Icon(Icons.add),
          ),
          SizedBox(
            height: 10,
          ),
          FloatingActionButton(
            heroTag: 'publish',
            onPressed: () {
              _subject.add("publish actice");
            },
            child: Icon(Icons.publish),
          )
        ],
      ),
    );
  }
}

/// I/flutter ( 6459): listener-1: Item1
// I/flutter ( 6459): listener-2: ITEM1
// I/flutter ( 6459): listener-2: ITEM2
// I/flutter ( 6459): listener-1: Item2
// I/flutter ( 6459): listener-2: ITEM3
// I/flutter ( 6459): listener-1: Item3
